<template>
  <!-- 合同管理 -->
  <el-container>
    <el-header>
      <div class="left-panel">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="add"
          v-auth-button="['add/contractManagement']"
        ></el-button>
      </div>
      <div class="right-panel">
        <div class="right-panel-search">
          <!-- <el-input
            v-model="searchValue.search"
            placeholder="合同名称"
            clearable
          ></el-input> -->
          <sc-table-select
            style="width: 100%"
            v-model="searchSelect.customer"
            :apiObj="apiObjCustomer"
            :table-width="700"
            clearable
            collapse-tags
            collapse-tags-tooltip
            :props="props"
            :params="customerForm"
            @change="changeCustomer"
          >
            <template #header="{ form, submit }">
              <el-form :model="customerForm">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input
                      v-model="customerForm.name"
                      placeholder="客户名称"
                      clearable
                      style="width: 100%"
                    ></el-input>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.startTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="开始时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerForm.endTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="结束时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="4">
                    <el-form-item width="100%">
                      <el-button type="primary" @click="submit">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <!-- <el-alert title="自定义FORM插糟 传递了form对象和提交方法" type="info" /> -->
            </template>
            <el-table-column
              prop="customerName"
              label="客户名称"
              min-width="150"
            ></el-table-column>
            <el-table-column
              prop="numbers"
              label="合同成交量"
              min-width="150"
            ></el-table-column>
          </sc-table-select>
          <el-select
            v-model="searchValue.status"
            placeholder="请选择合同状态"
            style="width: 100%"
            clearable
          >
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="未通过" :value="2" />
            <el-option label="审核中" :value="3" />
            <!-- <el-option label="作废" :value="4" /> -->
          </el-select>
          <el-select
            v-if="userList.length != 0"
            v-model="searchValue.applicationId"
            placeholder="请选择业务员"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
          <el-date-picker
            v-model="searchValue.startTime"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="开始时间"
            :teleported="false"
            style="width: 100%"
          ></el-date-picker>
          <el-date-picker
            v-model="searchValue.endTime"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="结束时间"
            :teleported="false"
            style="width: 100%"
          ></el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="upsearch"
          ></el-button>
        </div>
      </div>
    </el-header>
    <el-main class="nopadding">
      <scTable
        ref="table"
        :apiObj="apiObj"
        row-key="id"
        stripe
        @row-dblclick="handleRowDblclick"
        @filterType="filterType"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          label="ID"
          prop="id"
          width="60"
          fixed
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="合同编号"
          prop="num"
          min-width="150"
          fixed
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="客户名称"
          prop="customerName"
          min-width="250"
          fixed
          :show-overflow-tooltip="true"
        ></el-table-column>
        <!-- <el-table-column
          label="合同简称"
          prop="simpleName"
          min-width="150"
        ></el-table-column> -->
        <!-- <el-table-column label="客户名称" prop="customerName" min-width="150">
        </el-table-column>
        <el-table-column label="客户电话" prop="secondPhone" width="200">
        </el-table-column> -->
        <el-table-column label="合同类型" prop="typeName" width="100">
          <!--  1直销合同 2代理合同 3服务合同 4快销合同-->
          <!-- <template #default="scope">
            <p v-if="scope.row.type == 1">直销合同</p>
            <p v-if="scope.row.type == 2">代理合同</p>
            <p v-if="scope.row.type == 3">服务合同</p>
            <p v-if="scope.row.type == 4">快销合同</p>
          </template> -->
        </el-table-column>
        <el-table-column label="合同金额" prop="money" width="150">
          <template #default="scope">
            <p v-if="scope.row.refundMoney == 0">
              {{ scope.row.money }}元
              <span v-if="scope.row.isIncludeTax == 1"
                >(含税{{ scope.row.taxRate == 1 ? 6 : 13 }}%)</span
              >
            </p>
            <p v-if="scope.row.refundMoney != 0">
              {{ scope.row.money }}元(已退款{{ scope.row.refundMoney }}元
              <span v-if="scope.row.isIncludeTax == 1"
                >含税{{ scope.row.taxRate == 1 ? 6 : 13 }}%</span
              >)
            </p>
          </template>
        </el-table-column>
        <el-table-column label="收款方式" width="150">
          <template #default="scope">
            <p v-if="scope.row.paymentMethod == 1">
              预付款 +
              {{ scope.row.combination == 2 ? "到付" : "约定时间" }}
            </p>
            <p v-if="scope.row.paymentMethod == 2">到付</p>
            <p v-if="scope.row.paymentMethod == 3">约定时间</p>
          </template>
        </el-table-column>
        <el-table-column label="签订时间" prop="orderTime" width="120">
        </el-table-column>
        <!-- <el-table-column label="条款" prop="lessorArticle" min-width="150">
        </el-table-column> -->
        <el-table-column
          label="备注"
          prop="remark"
          :show-overflow-tooltip="true"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          label="业务员"
          prop="username"
          width="100"
          fixed="right"
        >
        </el-table-column>
        <!-- 0 待审核 1审核通过 2审核不通过 3作废 4删除 -->
        <el-table-column
          label="审核状态"
          prop="status"
          width="100"
          sortable
          fixed="right"
        >
          <template #default="scope">
            <p v-if="scope.row.status == 0">待审核</p>
            <p v-if="scope.row.status == 1" style="color: #67c23a">通过</p>
            <p v-if="scope.row.status == 2" style="color: #f56c6c">未通过</p>
            <p v-if="scope.row.status == 3" style="color: #ff9b31">审核中</p>
            <p v-if="scope.row.status == 4" style="color: #f56c6c">作废</p>
            <p v-if="scope.row.status == 5" style="color: #f56c6c">删除</p>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="250"
        >
          <template #default="scope">
            <el-button-group>
              <!-- <el-button
                text
                type="primary"
                size="small"
                @click="table_apply(scope.row, scope.$index)"
                v-if="
                  scope.row.status != 0 && scope.row.adminId == userInfo.userId
                "
                v-auth-button="['apply/contractManagement']"
                >申请修改</el-button
              > -->
              <el-button
                text
                size="small"
                type="primary"
                v-auth-button="['change/contractManagement']"
                v-if="scope.row.status != 0 && scope.row.isChange == 0"
                @click="table_change(scope.row, scope.$index)"
                >合同变更</el-button
              >
              <!-- <el-button
                text
                size="small"
                type="primary"
                @click="printPreview(scope.row)"
                >打印预览</el-button
              > -->
              <el-button
                text
                size="small"
                type="primary"
                @click="showProgress(scope.row)"
                >进度详情</el-button
              >
              <el-button
                text
                size="small"
                type="primary"
                @click="table_supplement(scope.row)"
                v-if="scope.row.status == 1"
                v-auth-button="['supplement/contractManagement']"
                >补充</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_applyLog(scope.row, scope.$index)"
                v-if="
                  scope.row.status != 0 && scope.row.adminId == userInfo.userId
                "
                v-auth-button="['applyLog/contractManagement']"
                >历史记录</el-button
              >
              <el-button
                text
                type="primary"
                size="small"
                @click="table_show(scope.row, scope.$index)"
                v-auth-button="['show/contractManagement']"
                >查看</el-button
              >

              <el-button
                text
                type="primary"
                size="small"
                @click="table_edit(scope.row, scope.$index)"
                v-auth-button="['edit/contractManagement']"
                v-if="scope.row.status == 0"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定作废吗？"
                @confirm="table_del(scope.row, scope.$index)"
                v-if="scope.row.status != 0"
              >
                <template #reference>
                  <el-button
                    text
                    type="primary"
                    size="small"
                    v-auth-button="['scrap/contractManagement']"
                    >作废</el-button
                  >
                </template>
              </el-popconfirm>
              <el-popconfirm
                title="确定删除吗？"
                @confirm="table_del(scope.row, scope.$index)"
                v-if="scope.row.status == 0"
              >
                <template #reference>
                  <el-button
                    text
                    type="primary"
                    size="small"
                    v-auth-button="['delete/contractManagement']"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </el-button-group>
          </template>
        </el-table-column>
      </scTable>
    </el-main>
  </el-container>

  <!-- 申请修改 -->
  <apply-dialog
    v-if="dialog.apply"
    ref="applyDialog"
    @success="handleSaveSuccess"
    @closed="dialog.apply = false"
  ></apply-dialog>

  <!-- 历史记录 -->
  <log-dialog
    v-if="dialog.log"
    ref="logDialog"
    @success="handleSaveSuccess"
    @closed="dialog.log = false"
  ></log-dialog>

  <print-dom ref="printDom" v-show="false" id="printDom"></print-dom>

  <contract-progress ref="contractProgress"></contract-progress>

  <supplement-dialog
    v-if="dialog.supplement"
    ref="supplementDialog"
    @success="handleSaveSuccess"
    @closed="dialog.supplement = false"
  ></supplement-dialog>
</template>

<script>
import print from "@/utils/print"
import printDom from "./components/printDom.vue"
import contractProgress from "./components/progress.vue"
import applyDialog from "@/components/applyDialog"
import logDialog from "./components/logDialog.vue"
import supplementDialog from "./components/supplementDialog.vue"
import { queryTypeByDic } from "@/utils/getData"
export default {
  name: "contractManagement",
  components: {
    applyDialog,
    printDom,
    contractProgress,
    logDialog,
    supplementDialog,
  },
  data () {
    return {
      dialog: {
        save: false,
        apply: false,
        log: false,
        supplement: false,
      },
      apiObj: this.$API.contract.getContracts,
      // params: {
      //   adminId: ''
      // },
      checkApi: this.$API.contract.checkContract, //审核api
      apiObjCustomer: this.$API.finance.plancollect.getCustomerNumbers,
      searchValue: {
        search: null,
        customerName: null,
        planStatus: null,
        startTime: null,
        endTime: null,
        customerId: null,
      },
      searchSelect: {},
      customerForm: {
        name: null,
        startTime: null,
        endTime: null,
      },
      props: {
        label: "customerName",
        value: "id",
      },
      // searchValue: {
      // 	search: null,
      // 	status: "",
      // 	customerId: "",
      // 	applicationId: "",
      // 	startTime: null,
      // 	endTime: null,
      // },
      userList: [],
      userInfo: {},
    }
  },
  beforeMount () {
    this.userInfo = this.$TOOL.data.get("USER_INFO")
    this.getUserList()
  },
  methods: {
    //打印预览
    printPreview (row) {
      this.getDetail(row.id)
    },

    async getUserList () {
      let res = await this.$API.user.getAdminList.get()
      this.userList = res.data
    },

    // 查看合同进度
    showProgress (row) {
      this.$refs.contractProgress.open(row)
    },
    // 获取合同详情
    async getDetail (id) {
      let { data } = await this.$API.contract.getContractById.post({
        id,
      })
      this.$refs.printDom.provideForm = data.customerData
      this.$refs.printDom.lessorArticle = data.lessorArticle
      this.$refs.printDom.quotesData = data.quotesData
      this.$refs.printDom.needForm = data.contractFit
      this.$refs.printDom.contactData = data
      this.$nextTick(() => {
        let dom = document.querySelector("#printDom")
        let clone = dom.cloneNode(true)
        clone.style.display = "block"
        print(clone)
      })
    },

    // 申请修改  -- 重新审核
    table_apply (row) {
      this.dialog.apply = true
      this.$nextTick(() => {
        this.$refs.applyDialog.open(row, 2)
      })
    },

    // 合同变更
    table_change (row) {
      this.$router.push({
        path: "/contract/contractManagement/contractChange",
        query: {
          id: row.id,
        },
      })
    },

    //添加
    add () {
      // this.dialog.save = true
      // this.$nextTick(() => {
      //   this.$refs.saveDialog.open()
      // })
      this.$router.push({
        path: "/contract/contractManagement/contractAdd",
        query: {
          mode: "add",
        },
      })
    },
    //编辑
    table_edit (row) {
      this.$router.push({
        path: "/contract/contractManagement/contractAdd",
        query: {
          mode: "edit",
          id: row.id,
        },
      })
    },

    // 历史记录（申请日志）
    table_applyLog (row) {
      this.dialog.log = true
      this.$nextTick(() => {
        this.$refs.logDialog.open(row)
      })
    },

    //查看
    table_show (row) {
      this.$router.push({
        // path: '/contract/contractManagement/contractDetail',
        path: "/contract/contractManagement/detailList",
        query: {
          id: row.id,
        },
      })
    },
    // 查看合同总详情
    table_showAll (row) {
      this.$router.push({
        path: "/contract/contractManagement/detailList",
        query: {
          id: row.id,
        },
      })
    },

    // 补充
    table_supplement (row) {
      this.dialog.supplement = true
      this.$nextTick(() => {
        this.$refs.supplementDialog.open(row)
      })
    },

    // 作废
    table_scrap (row) {
      this.table_del(row)
    },

    //删除
    async table_del (row) {
      let data = {
        ids: row.id,
        // projectId: row.projectId,
      }
      var res = await this.$API.contract.deleteContract.post(data)
      if (res.code == 200) {
        this.$refs.table.refresh()
        this.$message.success("操作成功")
      }
    },

    changeCustomer (val) {
      this.searchValue.customerId = val.id
    },
    //搜索
    upsearch () {
      this.$refs.table.upData(this.searchValue)
    },

    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = "页合计"
          return
        }
        if (column.property == "money") {
          const values = data.map((item) =>
            Number(item[column.property])
          )
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += " 元"
          } else {
            sums[index] = "N/A"
          }
        }
      })

      return sums
    },

    //本地更新数据
    handleSaveSuccess (data, mode) {
      if (mode == "add") {
        // this.$refs.table.refresh()
      } else if (mode == "edit") {
        // this.$refs.table.refresh()
      }
      this.$refs.table.refresh()
    },
    // 处理合同类型
    filterType (data) {
      let tableData = data
      queryTypeByDic("contractType").then((res) => {
        let list = res
        tableData.forEach((item) => {
          list.forEach((t_item) => {
            if (item.type == t_item.value) {
              item.typeName = t_item.name
            }
          })
        })
      })
    },

    // 双击表格
    handleRowDblclick (row) {
      this.table_show(row)
    },
  },
};
</script>

<style>
.cellClass {
  cursor: pointer;
}
</style>
